package com.diyphonegadgets.yandroidcontroller.wifi;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import org.json.JSONObject;

import android.util.Log;

public class TCPServer implements Runnable{
	
    public static final String SERVERIP = "10.0.2.2";
         
    public void run() {
    	

    
    	
         try {
        	 //Log.d("TCP","S: Connecting...");
              
             ServerSocket serverSocket = new ServerSocket(CommandManager.receivePort);
             while (true) {
            	 
            	 
            	  
            	  Socket client = serverSocket.accept();
            	 // Log.d("TCP","S: Receiving...");

            	  try {
                      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                      String str = in.readLine();
                   
       		 
                     // Log.d("TCP","S: Received: '" + str + "'");
                
            	      if( CommandManager.listener!=null) {

            	    	  
            	    	    JSONObject json = new JSONObject(str);

                    	  CommandManager.listener.onCommandChanged(json);
                    	  
                 		 Thread.sleep(CommandManager.updateInterval);

       		
            	      }
                      
                      
                      
                    } catch(Exception e) {
                        Log.d("","S: Error");
                        e.printStackTrace();
                    } finally {
                    	client.close();
                        //Log.d("","S: Done.");
                    }

             }
              
         } catch (Exception e) {
             Log.d("","S: Error");
             e.printStackTrace();
         }
    }
    
 
}